import * as _ from 'lodash-es'
import { CACHE_KEY, useCache } from '@/hooks/basic/useCache'
import { isDark } from '@/utils/basic-common/is'
import { ThemeKey, ThemeOpt } from './types'
import primary from './src/primary'
import purple from './src/purple'

export * from './types'

export const colorTheme: { [key: string]: ThemeOpt } = {
  primary,
  purple,
}

export const colorThemes: ThemeOpt[] = Object.keys(colorTheme).map(key => {
  return colorTheme[key]
})

const { wsCache } = useCache()

class AppTheme {
  themeKey: ThemeKey  // 当前主题
  themeOpt: ThemeOpt  // 当前主题配置
  isDark: boolean  // 是否暗色模式
  isGrey: boolean  // 是否灰度模式

  constructor() {
    this.themeKey = 'primary'
    this.themeOpt = _.cloneDeep(colorTheme.primary)
    this.isDark = false
    this.isGrey = false
  }

  init() {
    this.themeKey = wsCache.get(CACHE_KEY.THEME) || 'primary'
    this.themeOpt = _.merge({}, colorTheme.primary, colorTheme[this.themeKey] || {})
    this.isDark = wsCache.get(CACHE_KEY.IS_DARK) || isDark() || false
    this.resetVars()
  }

  setTheme(themeKey?: ThemeKey, themeOpt?: any) {
    this.themeKey = themeKey || this.themeKey
    this.themeOpt = _.merge(this.themeOpt, colorTheme[this.themeKey] || {}, themeOpt || {})
    this.resetVars()
  }

  setIsDark(isDark?: boolean) {
    this.isDark = ![null, undefined].includes(isDark) ? isDark : this.isDark
    this.resetVars()
  }

  setIsGray(isGrey?: boolean) {
    this.isGrey = isGrey || false

    const el = document.documentElement
    if (this.isGrey) {
      el.classList.add('grey')
    } else {
      el.classList.remove('grey')
    }
  }

  resetVars() {
    const el = document.documentElement

    Object.keys(this.themeOpt.variables).forEach(key => {
      el.style.setProperty(key, this.themeOpt.variables[key])
    })
    wsCache.set(CACHE_KEY.THEME, this.themeKey)

    if (this.isDark) {
      Object.keys(this.themeOpt.variablesDark).forEach(key => {
        el.style.setProperty(key, this.themeOpt.variablesDark[key])
      })
      el.classList.add('dark')
    } else {
      el.classList.remove('dark')
    }
    wsCache.set(CACHE_KEY.IS_DARK, this.isDark)
  }
}

export const appTheme = new AppTheme()
